package com.wdb.common.configurer.feign;

import com.netflix.hystrix.exception.HystrixBadRequestException;
import com.wdb.common.constant.Constant;
import com.wdb.common.util.JacksonUtils;
import feign.Response;
import feign.codec.ErrorDecoder;
import org.springframework.util.ObjectUtils;

import java.util.Map;
import java.util.Objects;

import static feign.FeignException.errorStatus;

public class FeignDecoder implements ErrorDecoder {
    @Override
    public Exception decode(String methodKey, Response response) {
        int status = response.status();
        if (Objects.equals(400, status)) {
            try {
                Map map = JacksonUtils.parse(response.body().asInputStream(), Map.class);

                if (Objects.isNull(map)) {
                    return new HystrixBadRequestException(Constant.Error.ERROR_BUSINESS);
                }

                Object error = map.get(Constant.Error.ERROR_KEY);
                if (ObjectUtils.isEmpty(error)) {
                    return new HystrixBadRequestException(Constant.Error.ERROR_BUSINESS);
                }
                return new HystrixBadRequestException(error.toString());
            } catch (Exception e) {
                e.printStackTrace();
                return new HystrixBadRequestException(Constant.Error.ERROR_BUSINESS);
            }
        }
        return errorStatus(methodKey, response);
    }
}
